package 网络编程.Text;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPText2 {
    public static void main(String[] args) throws IOException {
        /**
         * 按照下面的要求实现程序
         * UDP发送数据:数据来自键盘录入，直到输入的数据是886，发送数据结束
         * UDP接收数据:因为接收端不知道发送端什么时候停止发送，故采用死循环接收
         */
        //创建接收端
        DatagramSocket ds=new DatagramSocket(18895);

            //创建一个箱子接收
            byte[] bytes = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
        while (true) {
            ds.receive(dp);
            //数据解析
            byte[] data = dp.getData();
            InetAddress address = dp.getAddress();
            int port = dp.getPort();
            int length = dp.getLength();
            System.out.println("该数据为:" + new String(data, 0, length));
            System.out.println("该数据是从IP为:" + address + "端口为:" + port + "发出来的");
        }
    }
}
